<template>
  <div class="addBrand-container">
    <div class="container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        :inline="true"
        label-width="180px"
        class="demo-ruleForm"
      >
        <div>
          <el-form-item label="组合药名称:" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请填写组合药名称"
              maxlength="14"
            />
          </el-form-item>
          <el-form-item label="组合药分类:" prop="idType">
            <el-select
              v-model="ruleForm.idType"
              placeholder="请选择组合药分类"
              @change="$forceUpdate()"
            >
              <el-option
                v-for="(item, index) in setMedicineList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="组合药价格:" prop="price">
            <el-input v-model="ruleForm.price" placeholder="请设置组合药价格" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="组合药的药品:"  required>
            <el-form-item>
              <div class="AddMedicine">
                <span
                  v-if="medicineTable.length == 0"
                  class="addBut"
                  @click="openAddMedicine('new')"
                  style="background-color: aquamarine;"
                >
                  + 添加药品</span
                >
                <div v-if="medicineTable.length != 0" class="content">
                  <div
                    class="addBut"
                    style="margin-bottom: 20px"
                    @click="openAddMedicine('change')"
                  >
                    + 添加药品
                  </div>
                  <div class="table">
                    <el-table :data="medicineTable" style="width: 100%">
                      <el-table-column
                        prop="name"
                        label="名称"
                        width="180"
                        align="center"
                      />
                      <el-table-column
                        prop="price"
                        label="原价"
                        width="180"
                        align="center"
                      >
                        <template slot-scope="scope">
                          {{ (Number(scope.row.price).toFixed(2) * 100) / 100 }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="address"
                        label="份数"
                        align="center"
                      >
                        <template slot-scope="scope">
                          <el-input-number
                            v-model="scope.row.copies"
                            size="small"
                            :min="1"
                            :max="99"
                            label="描述主治功能"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="address"
                        label="操作"
                        width="180px;"
                        align="center"
                      >
                        <template slot-scope="scope">
                          <el-button
                            type="text"
                            size="small"
                            class="delBut non"
                            @click="delDishHandle(scope.$index)"
                          >
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="组合药图片:" required prop="image">
            <image-upload :prop-image-url="imageUrl" @imageChange="imageChange">
              图片大小不超过2M<br />仅能上传 PNG JPEG JPG类型图片<br />建议上传200*200或300*300尺寸的图片
            </image-upload>
          </el-form-item>
        </div>
        <!-- <el-form-item
          label="商品码:"
          prop="code"
        >
          <el-input
            v-model="ruleForm.code"
            placeholder="请输入商品码"
          />
        </el-form-item> -->
        <div class="address">
          <el-form-item label="组合药描述（主治功能）:">
            <el-input
              v-model="ruleForm.description"
              type="textarea"
              :rows="3"
              maxlength="200"
              placeholder="组合药描述，最长200字"
            />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-form-item>
            <el-button @click="() => $router.back()"> 取消 </el-button>
            <el-button
              type="primary"
              :class="{ continue: actionType === 'add' }"
              @click="submitForm('ruleForm', false)"
            >
              保存
            </el-button>
            <el-button
              v-if="actionType == 'add'"
              type="primary"
              @click="submitForm('ruleForm', true)"
            >
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-dialog
      v-if="dialogVisible"
      title="添加药品"
      class="addDishList"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-input
        v-model="value"
        class="seachDish"
        placeholder="请输入药品名称进行搜索"
        style="width: 293px; height: 40px"
        size="small"
        clearable
      >
        <i
          slot="prefix"
          class="el-input__icon el-icon-search"
          style="cursor: pointer"
          @click="seachHandle"
        />
      </el-input>
      <AddMedicine
        v-if="dialogVisible"
        ref="AddMedicine"
        :check-list="checkList"
        :seach-key="seachKey"
        :medicine-list="chinesewesternchineseList"
        @checkList="getCheckList"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addTableList">添 加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Component, Vue } from 'vue-property-decorator'
import HeadLable from '@/components/HeadLable/index.vue'
import ImageUpload from '@/components/ImgUpload/index.vue'
import AddMedicine from './components/AddChineseWesternMedicine.vue'
import {
  queryById,
  addd,
  editsss,
} from '@/api/setMedicine'
import { getCategoryList } from '@/api/category'

@Component({
  name: 'addShop',
  components: {
    HeadLable,
    AddMedicine,
    ImageUpload,
  },
})
export default class extends Vue {
  value = ''
  setMedicineList = []
  seachKey = ''
  chinesewesternchineseList = []
  imageUrl = ''
  actionType = ''
  medicineTable = []
  dialogVisible = false
  checkList = []
  ruleForm = {
    name: '',
    categoryId: '',
    price: '',
    code: '',
    image: '',
    description: '',
    chinesewesternchineseList: [],
    status: true,
    idType: '',
  }

  get rules() {
    return {
      name: {
        required: true,
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请输入组合药名称'))
          } else {
            const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
            if (!reg.test(value)) {
              callback(new Error('套餐名称输入不符，请输入2-20个字符'))
            } else {
              callback()
            }
          }
        },
        trigger: 'blur',
      },
      idType: {
        required: true,
        message: '请选择组合药分类',
        trigger: 'change',
      },
      image: {
        required: true,
        message: '药品图片不能为空',
      },
      price: {
        required: true,
        // 'message': '请输入组合药价格',
        validator: (rules, value, callback) => {
          const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
          if (!reg.test(value) || Number(value) <= 0) {
            callback(
              new Error(
                '组合药价格格式有误，请输入大于零且最多保留两位小数的金额'
              )
            )
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
      code: { required: true, message: '请输入商品码', trigger: 'blur' },
    }
  }

  created() {
    this.getMedicineTypeList()
    this.actionType = this.$route.query.id ? 'edit' : 'add'
    if (this.actionType == 'edit') {
      this.init()
    }
  }

  async init() {
    queryById(this.$route.query.id).then((res) => {
      if (res && res.data && res.data.code === 1) {
        this.ruleForm = res.data.data
        this.ruleForm.status = res.data.data.status == '1'
        this.ruleForm.price = res.data.data.price
        // this.imageUrl = `http://172.17.2.120:8080/common/download?name=${res.data.data.image}`
        this.imageUrl = res.data.data.image
        this.checkList = res.data.data.setmedicineMedicines
        this.medicineTable = res.data.data.setmedicineMedicines.reverse()
        this.ruleForm.idType = res.data.data.categoryId
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }
  seachHandle() {
    this.seachKey = this.value
  }
  // 获取组合药分类
  getMedicineTypeList() {
    getCategoryList({ type: 2, page: 1, pageSize: 1000 }).then((res) => {
      if (res && res.data && res.data.code === 1) {
        this.setMedicineList = res.data.data.map((obj) => ({
          ...obj,
          idType: obj.id,    
        }))
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }

  // 通过组合药ID获取菜品列表分类
  //  getMedicineList (id:number) {
  //   getMedicineListType({id}).then(res => {
  //     if (res.data.code == 200) {
  //       const { data } = res.data
  //       this.chinesewesternchineseList = data
  //     } else {
  //       this.$message.error(res.data.desc)
  //     }
  //   })
  // }

  // 删除组合药菜品
  delDishHandle(index) {
    this.medicineTable.splice(index, 1)
    this.checkList = this.medicineTable
    // this.checkList.splice(index, 1)
  }

  // 获取添加药品数据 - 确定加菜倒序展示
  getCheckList(value) {
    this.checkList = [...value].reverse()
  }

  // 添加药品
  openAddMedicine(st) {
    this.seachKey = ''
    this.dialogVisible = true
  }
  // 取消添加药品
  handleClose(done) {
    // this.$refs.AddMedicine.close()
    this.dialogVisible = false
    this.checkList = JSON.parse(JSON.stringify(this.medicineTable))
    // this.dialogVisible = false
  }

  // 保存添加药品列表
  addTableList() {
    this.medicineTable = JSON.parse(JSON.stringify(this.checkList))
    this.medicineTable.forEach((n) => {
      n.copies = 1
    })
    this.dialogVisible = false
  }

  submitForm(formName, st) {
    this.$refs[formName].validate((valid) => {
      if (valid) {
        if (this.medicineTable.length === 0) {
          return this.$message.error('组合药下药品不能为空')
        }
        if (!this.ruleForm.image)
          return this.$message.error('组合药图片不能为空')
        let prams = { ...this.ruleForm }
        prams.setmedicineMedicines = this.medicineTable.map((obj) => ({
          copies: obj.copies,
          dishId: obj.dishId,
          name: obj.name,
          price: obj.price,
        }))
        prams.status =
          this.actionType === 'add' ? 0 : this.ruleForm.status ? 1 : 0
        prams.categoryId = this.ruleForm.idType
        // delete prams.chinesewesternchineseList
        console.log('this.ruleForm.idType:',this.ruleForm.idType);
        if (this.actionType == 'add') {
          delete prams.id
          console.log("this.actionType",this.actionType);
          addd(prams)
            .then((res) => {
              if (res && res.data && res.data.code === 1) {
                this.$message.success('组合药添加成功！')
                if (!st) {
                  this.$router.push({ path: '/setmedicine' })
                } else {
                  this.$refs.ruleForm.resetFields()
                  this.chinesewesternchineseList = []
                  this.medicineTable = []
                  this.ruleForm = {
                    name: '',
                    categoryId: '',
                    price: '',
                    code: '',
                    image: '',
                    description: '',
                    chinesewesternchineseList,
                    status: true,
                    id: '',
                    idType: '',
                  }
                  this.imageUrl = ''
                }
              } else {
                this.$message.error(res.data.msg)
              }
            })
            .catch((err) => {
              this.$message.error('请求出错了：' + err.message)
            })
        } else {
          console.log("edits")
          delete prams.updateTime
            editsss(prams)
            .then((res) => {
              if (res.data.code === 1) {
                this.$message.success('组合药修改成功！')
                this.$router.push({ path: '/setmedicine' })
              } else {
                this.$message.error(res.data.desc || res.data.message)
              }
            })
            .catch((err) => {
              this.$message.error('请求出错了：' + err.message)
            })
        }
      } else {
        console.log('error submit!!')
        return false
      }
    })
  }

  imageChange(value) {
    this.ruleForm.image = value
  }
}
</script>
<style>
.avatar-uploader .el-icon-plus:after {
  position: absolute;
  display: inline-block;
  content: ' ' !important;
  left: calc(50% - 20px);
  top: calc(50% - 40px);
  width: 40px;
  height: 40px;
  background: url('./../../assets/icons/icon_upload@2x.png') center center
    no-repeat;
  background-size: 20px;
}
</style>
<style lang="scss">
// .el-form-item__error {
//   top: 90%;
// }
.addBrand-container {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #ffc200;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }

  .avatar {
    width: 200px;
    height: 160px;
    display: block;
  }

  // .el-form--inline .el-form-item__content {
  //   width: 293px;
  // }

  .el-input {
    width: 293px;
  }

  .address {
    .el-form-item__content {
      width: 777px !important;
    }
  }
  .el-input__prefix {
    top: 2px;
  }

  .AddMedicine {
    .el-input {
      width: 130px;
    }

    .el-input-number__increase {
      border-left: solid 1px #fbe396;
      background: #fffbf0;
    }

    .el-input-number__decrease {
      border-right: solid 1px #fbe396;
      background: #fffbf0;
    }

    input {
      border: 1px solid #fbe396;
    }

    .table {
      border: solid 1px #ebeef5;
      border-radius: 3px;

      th {
        padding: 5px 0;
      }

      td {
        padding: 7px 0;
      }
    }
  }

  .addDishList {
    .seachDish {
      position: absolute;
      top: 12px;
      right: 20px;
    }

    .el-dialog__footer {
      padding-top: 27px;
    }

    .el-dialog__body {
      padding: 0;
      border-bottom: solid 1px #efefef;
    }
    .seachDish {
      .el-input__inner {
        height: 40px;
        line-height: 40px;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;

    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      min-height: 500px;

      .subBox {
        padding-top: 30px;
        text-align: center;
        border-top: solid 1px $gray-5;
      }
      .el-input {
        width: 350px;
      }
      .AddMedicine {
        width: 777px;

        .addBut {
          background: #ffc200;
          display: inline-block;
          padding: 0px 20px;
          border-radius: 3px;
          line-height: 40px;
          cursor: pointer;
          border-radius: 4px;
          color: #333333;
          font-weight: 500;
        }

        .content {
          background: #fafafb;
          padding: 20px;
          border: solid 1px #d8dde3;
          border-radius: 3px;
        }
      }
    }
  }
}
</style>
